package com.example.myjavalib
import ohos.agp.components.Component
import ohos.agp.components.LayoutScatter
import ohos.agp.components.Text
import ohos.agp.utils.LayoutAlignment
import ohos.agp.window.dialog.CommonDialog
import ohos.agp.window.dialog.IDialog
import ohos.app.Context
import ohos.multimodalinput.event.KeyEvent

/**
 * 自定义提示弹窗
 *
 * @since 2021-04-12
 * https://gitee.com/chinasoft_ohos/HiPermission/blob/master/library/src/main/java/me/weyye/hipermission/AlertDialog.java
 */
class AlertDialog(context: Context?, resId: Int, componentId: ComponentId) : CommonDialog(context) {
    private var tvTitle: Text? = null
    private var tvContent: Text? = null
    private var tvCancel: Text? = null
    private var tvSure: Text? = null

    data class ComponentId(val tvTitle: Int, val tvContent: Int, val tvCancel: Int, val tvSure: Int)


    init {
        setTransparent(true)
        setAlignment(LayoutAlignment.CENTER)
        val contentView = LayoutScatter.getInstance(context)
            .parse(resId, null, true)
        contentCustomComponent = contentView
        initView(componentId)
        siteRemovable(false)
        siteKeyboardCallback { iDialog: IDialog?, keyEvent: KeyEvent? -> true }
    }

    private fun initView(componentId: ComponentId) {
        val component = contentCustomComponent
        tvTitle = component.findComponentById<Component>(componentId.tvTitle) as Text
        tvContent = component.findComponentById<Component>(componentId.tvContent) as Text
        tvCancel = component.findComponentById<Component>(componentId.tvCancel) as Text
        tvSure = component.findComponentById<Component>(componentId.tvSure) as Text

        tvCancel!!.clickedListener = Component.ClickedListener { hide() }
        tvSure!!.clickedListener = Component.ClickedListener { hide() }
    }

    /**
     * 设置标题
     *
     * @param title 标题
     */
    fun setTitle(title: String?) {
        tvTitle!!.text = title
    }

    /**
     * 设置内容
     *
     * @param content 内容
     */
    fun setContent(content: String?) {
        tvContent!!.text = content
    }

    /**
     * 设置取消按钮文字和点击事件监听
     *
     * @param cancel 按钮文字
     * @param listener 点击事件监听
     */
    fun setCancel(cancel: String?, listener: Component.ClickedListener?) {
        tvCancel!!.text = cancel
        tvCancel!!.clickedListener = Component.ClickedListener {
            hide()
            listener?.onClick(tvCancel)
        }
    }

    /**
     * 设置确定按钮文字和点击事件监听
     *
     * @param sure 按钮文字
     * @param listener 点击事件监听
     */
    fun setSure(sure: String?, listener: Component.ClickedListener?) {
        tvSure!!.text = sure
        tvSure!!.clickedListener = Component.ClickedListener {
            hide()
            listener?.onClick(tvSure)
        }
    }
}